package com.baidumap.administrator.happystudy.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.dialog.loadingDialog.LoadingDialogUtil;
import com.ab.dialog.materialDialog.MaterialDialogUtil;
import com.ab.http.OnMessageResponse;
import com.ab.util.AbStrUtil;
import com.ab.util.ToastUtil;
import com.ab.view.clear_edit_text.ClearEditText;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.broacast.AppBroadcastReceiver;
import com.baidumap.administrator.happystudy.module.address.activity.Activity_ChangeAddress;
import com.baidumap.administrator.happystudy.module.person.model.PersonInfo;
import com.baidumap.administrator.happystudy.module.person.model.UpdateHeadImage;
import com.baidumap.administrator.happystudy.module.person.model.UpdateInfo;
import com.baidumap.administrator.happystudy.utils.GlideUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.OnClick;

import static com.baidumap.administrator.happystudy.R.id.tv_sex;

/**
 * 描述：我的信息
 * 作者：xiaoxing on 17/4/10 22:09
 * 邮箱：2235445233@qq.com
 */
public class PersonInfoActivity extends AppBaseActivity implements OnMessageResponse {


    @Bind(R.id.img_tou_xiang)
    ImageView imgTouXiang;
    @Bind(R.id.ll_tou_xiang)
    LinearLayout llTouXiang;
    @Bind(R.id.tv_nickname)
    TextView tvNickname;
    @Bind(R.id.ll_nick_name)
    LinearLayout llNickName;
    @Bind(tv_sex)
    TextView tvSex;
    @Bind(R.id.tv_tel)
    TextView tvTel;
    @Bind(R.id.ll_tel)
    LinearLayout llMTel;
    @Bind(R.id.tv_school)
    TextView tvSchool;
    @Bind(R.id.tv_xueyuan)
    TextView tvXueYuan;
    @Bind(R.id.tv_nianji)
    TextView tvNianji;
    @Bind(R.id.img_sex)
    ImageView imgSex;

    /**
     * 头像名称
     */
    private static final String IMAGE_FILE_NAME = "image.jpg";
    /**
     * 请求码
     */
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;

    @Override
    public int bindLayout() {
        return R.layout.activity_person_info;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        setHeaderBack();
        setHeaderTitle(R.string.wo_de_xin_xi);
        LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
        Api.memberInfo(this, sHelper.getString(Constant.UID));
    }

    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {
        if (url.equals(Constant.USER_MEMBER_INFO) && jo != null) {
            PersonInfo personInfo = new PersonInfo(jo.toString());

            if (personInfo != null) {


                if (personInfo.getCode().equals("200")) {
                    PersonInfo.DataBean dataBean = personInfo.getData();


                    GlideUtil.displayImg(this, Constant.DOMAIN + dataBean.getCover(), imgTouXiang);
                    tvNickname.setText(dataBean.getNick_name());

                    if (dataBean.getSex().equals("1")) {

                        tvSex.setText("男生");
                        imgSex.setImageDrawable(getResources().getDrawable(R.mipmap.boy));
                    } else {
                        tvSex.setText("女生");
                        imgSex.setImageDrawable(getResources().getDrawable(R.mipmap.girl));
                    }
                    tvTel.setText(dataBean.getMobile());
                    tvSchool.setText(dataBean.getSchool());
                    tvXueYuan.setText(dataBean.getSection());
                    tvNianji.setText(dataBean.getGrade());
                } else {
                    ToastUtil.showMessage(this, personInfo.getMsg());
                }
            }

        }
        if (url.equals(Constant.USER_UPDATE_USER_INFO) && jo != null) {
            UpdateInfo updateInfo = new UpdateInfo(jo.toString());

            if (updateInfo != null) {


                if (updateInfo.getCode().equals("200")) {
                    ToastUtil.showMessage(PersonInfoActivity.this, "修改成功");
                    Api.memberInfo(this, sHelper.getString(Constant.UID));
                } else {
                    ToastUtil.showMessage(this, updateInfo.getMsg());
                }
            }

        }
        if (url.equals(Constant.UPLOAD_MEMBER_IMAGE) && jo != null) {
            UpdateHeadImage updateHeadImage = new UpdateHeadImage(jo.toString());

            if (updateHeadImage != null) {

                if (updateHeadImage.getCode().equals("200")) {
                    ToastUtil.showMessage(PersonInfoActivity.this, "修改成功");
                    sHelper.putString(Constant.COVER, updateHeadImage.getData().getCover());
                    Api.memberInfo(this, sHelper.getString(Constant.UID));
                    AppBroadcastReceiver.sendAppBroadcastReceiverMessage(this, Constant.INTENT_KEY.UPDATE_USER_INFO);

                } else {
                    ToastUtil.showMessage(this, updateHeadImage.getMsg());
                }
            }

        }
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }


    @OnClick({R.id.ll_sex, R.id.ll_tou_xiang, R.id.ll_nick_name, R.id.ll_tel, R.id.ll_address, R.id.ll_school, R.id.ll_xueyuan, R.id.ll_grade})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.ll_sex:
                modifySex();
                break;
            case R.id.ll_tou_xiang:
                modifyTouXiang();
                break;
            case R.id.ll_nick_name:
                modifyNickname();
                break;
            case R.id.ll_tel:
                modifyTel();
                break;
            case R.id.ll_address:
                startActivity(Activity_ChangeAddress.class);
                break;
            case R.id.ll_school:
                modifySchool();
                break;
            case R.id.ll_xueyuan:
                modifyXueyuan();
                break;
            case R.id.ll_grade:
                modifyGrade();
                break;
        }
    }

    private void modifySex() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_sex, null);

        TextView tv_sex_nan = (TextView) viewSex.findViewById(R.id.tv_sex_nan);
        TextView tv_sex_woman = (TextView) viewSex.findViewById(R.id.tv_sex_woman);
        tv_sex_nan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvSex.setText("男生");
                MaterialDialogUtil.dismissDialogButton();

                updateInfo();
            }
        });
        tv_sex_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvSex.setText("女生");
                MaterialDialogUtil.dismissDialogButton();
                updateInfo();
            }
        });
        MaterialDialogUtil.showDialog_OneButton(this, "修改性别", viewSex);
    }

    private void modifyNickname() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_nickname, null);

        final ClearEditText ced_nickname = (ClearEditText) viewSex.findViewById(R.id.ced_nickname);

        MaterialDialogUtil.showDialogTwoButton(this, "修改昵称", viewSex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickname = getEidtTextValue(ced_nickname);
                if (AbStrUtil.isEmpty(nickname)) {

                    ToastUtil.showMessage(PersonInfoActivity.this, "昵称不能为空");
                    return;
                }
                tvNickname.setText(nickname);
                MaterialDialogUtil.dismissDialogButton();

                updateInfo();
            }
        });
    }

    private void modifySchool() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_tel, null);

        final ClearEditText ced_nickname = (ClearEditText) viewSex.findViewById(R.id.ced_nickname);
        ced_nickname.setHint("请输入学校");
        MaterialDialogUtil.showDialogTwoButton(this, "修改学校", viewSex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickname = getEidtTextValue(ced_nickname);
                if (AbStrUtil.isEmpty(nickname)) {

                    ToastUtil.showMessage(PersonInfoActivity.this, "学校不能为空");
                    return;
                }
                tvSchool.setText(nickname);
                MaterialDialogUtil.dismissDialogButton();
                updateInfo();
            }
        });
    }

    private void modifyXueyuan() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_tel, null);

        final ClearEditText ced_nickname = (ClearEditText) viewSex.findViewById(R.id.ced_nickname);
        ced_nickname.setHint("请输入学院");
        MaterialDialogUtil.showDialogTwoButton(this, "修改学院", viewSex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickname = getEidtTextValue(ced_nickname);
                if (AbStrUtil.isEmpty(nickname)) {

                    ToastUtil.showMessage(PersonInfoActivity.this, "院校不能为空");
                    return;
                }
                tvXueYuan.setText(nickname);
                MaterialDialogUtil.dismissDialogButton();
                updateInfo();
            }
        });
    }

    private void modifyGrade() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_tel, null);

        final ClearEditText ced_nickname = (ClearEditText) viewSex.findViewById(R.id.ced_nickname);
        ced_nickname.setHint("请输入年级");
        MaterialDialogUtil.showDialogTwoButton(this, "修改年级", viewSex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickname = getEidtTextValue(ced_nickname);
                if (AbStrUtil.isEmpty(nickname)) {

                    ToastUtil.showMessage(PersonInfoActivity.this, "年级不能为空");
                    return;
                }
                tvNianji.setText(nickname);
                MaterialDialogUtil.dismissDialogButton();
                updateInfo();
            }
        });
    }

    private void modifyTel() {
        LayoutInflater layoutInflaterSex = LayoutInflater.from(this);
        View viewSex = layoutInflaterSex.inflate(R.layout.dialog_tel, null);

        final ClearEditText ced_nickname = (ClearEditText) viewSex.findViewById(R.id.ced_nickname);

        MaterialDialogUtil.showDialogTwoButton(this, "修改联系方式", viewSex, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickname = getEidtTextValue(ced_nickname);
                if (AbStrUtil.isEmpty(nickname)) {

                    ToastUtil.showMessage(PersonInfoActivity.this, "联系方式不能为空");
                    return;
                }
                tvTel.setText(nickname);
//                MaterialDialogUtil.dismissDialogButton();
//                updateInfo(tvSex, getTextViewValue(tvTel));
                updateInfo();
            }
        });
    }

    private void updateInfo() {
        String sex = getTextViewValue(tvSex);
        String nickname = getTextViewValue(tvNickname);
        String tel = getTextViewValue(tvTel);
        String school = getTextViewValue(tvSchool);
        String xueyuan = getTextViewValue(tvXueYuan);
        String nianji = getTextViewValue(tvNianji);
        if (sex.equals("男生")) {
            sex = "1";
            imgSex.setImageDrawable(getResources().getDrawable(R.mipmap.boy));
        } else {
            sex = "2";
            imgSex.setImageDrawable(getResources().getDrawable(R.mipmap.girl));
        }
        LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
        Api.updateMemberInfo(PersonInfoActivity.this, sHelper.getString(Constant.UID), nickname, sex, school, xueyuan, nianji, "");
    }

    private void modifyTouXiang() {
        LayoutInflater layoutInflaterTouXiang = LayoutInflater.from(this);
        View viewTouXiang = layoutInflaterTouXiang.inflate(R.layout.dialog_tou_xiang, null);

        TextView tv_pai_zhao = (TextView) viewTouXiang.findViewById(R.id.tv_pai_zhao);
        TextView tv_xiang_ce = (TextView) viewTouXiang.findViewById(R.id.tv_xiang_ce);
        tv_pai_zhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentFromCapture = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                // 判断存储卡是否可以用，可用进行存储
                String state = Environment
                        .getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    File path = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    File file = new File(path, IMAGE_FILE_NAME);
                    intentFromCapture.putExtra(
                            MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(file));
                }

                startActivityForResult(intentFromCapture,
                        CAMERA_REQUEST_CODE);

            }
        });
        tv_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intentFromGallery = new Intent();
                intentFromGallery.setType("image/*"); // 设置文件类型
                intentFromGallery
                        .setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intentFromGallery,
                        IMAGE_REQUEST_CODE);
            }
        });
        MaterialDialogUtil.showDialog_OneButton(this, "修改头像", viewTouXiang);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        MaterialDialogUtil.dismissDialogButton();
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    // 判断存储卡是否可以用，可用进行存储
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        File path = Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                        File tempFile = new File(path, IMAGE_FILE_NAME);
                        startPhotoZoom(Uri.fromFile(tempFile));
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case RESULT_REQUEST_CODE: // 图片缩放完成后
                    if (data != null) {
                        getImageToView(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 340);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param
     */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(this.getResources(), photo);
            imgTouXiang.setImageDrawable(drawable);

            Api.userMemberImage(this, sHelper.getString(Constant.UID), compressImage(photo));
        }
    }


    /**
     * 将Bitmap转换成Base64
     *
     * @param bit
     * @return
     */
    public String getImgStr(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 压缩图片（质量压缩）
     *
     * @param image
     */

    public static File compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;

        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
//        long length = baos.toByteArray().length;
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片


        File file = new File(Environment.getExternalStorageDirectory() + "/temp.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return file;
    }
}
